<template>
  <div ref="content" class="content">
    <el-row :gutter="20" :class="{header:needTagsView && fixedHeader}">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="roleName"
            placeholder="请输入角色"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="tree"
            :data="roleOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>
        <el-table
          v-loading="loading"
          :data="tableData.filter(data => !search || data.houseResidentialQuarters.toLowerCase().includes(search.toLowerCase()))"
          tooltip-effect="dark"
          height="600px"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            prop="userId"
            label="用户id"
          />
          <el-table-column
            prop="userName"
            label="用户名"
          />
          <el-table-column
            prop="userPassword"
            label="用户密码"
          />
          <el-table-column
            key="userState"
            label="账号状态"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.userState"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="userPhone"
            label="用户手机号"
          />
          <el-table-column
            prop="userMail"
            label="用户邮箱"
          />
          <el-table-column
            prop="createTime"
            label="创建时间"
          />
          <el-table-column
            fixed="right"
            width="130"
            label="操作"
          >
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="查看此用户的数据" placement="bottom-end">
                <el-button
                  type="text"
                  size="small"
                  @click.native.prevent="lookUp(scope.$index, tableData)"
                >
                  查看
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="修改此用户的数据" placement="bottom-end">
                <el-button
                  type="text"
                  size="small"
                  @click.native.prevent="update(scope.$index, tableData)"
                >
                  修改
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除此用户的数据" placement="bottom-end">
                <el-button
                  type="text"
                  size="small"
                  @click.native.prevent="deleteRow(scope.$index, tableData)"
                >
                  删除
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="text-align:center"
          background
          :page-sizes="[20, 40, 80, 100, 200]"
          :page-size="20"
          layout="sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
    <!-- dialog 查看用户信息 -->
    <el-dialog title="用户信息" :visible.sync="dialogVisible" :before-close="formClose" append-to-body width="600px">
      <el-form ref="form" :model="form" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户系统ID">
              <el-input v-model="form.userId" readonly maxlength="15" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="form.userName" :readonly="!formState" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户密码">
              <el-input v-model="form.userPassword" autocomplete="off" :readonly="!formState" maxlength="18" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态">
              <el-radio v-model="form.userState" :label="0" :disabled="!formState" @change="handleUserState">启用</el-radio>
              <el-radio v-model="form.userState" :label="1" :disabled="!formState" @change="handleUserState">停用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户手机号">
              <el-input v-model="form.userPhone" autocomplete="off" :readonly="!formState" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户邮箱">
              <el-input v-model="form.userMail" autocomplete="off" :readonly="!formState" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="创建时间">
          <el-input v-model="form.createTime" autocomplete="off" readonly />
        </el-form-item>
      </el-form>
      <div v-if="formState" slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getAllRole, getAllUser, updateUser, deleteUser } from '@/api/user'
export default {
  components: {},
  data() {
    return {
      // 加载状态
      loading: false,
      // 总数
      total: 0,
      // 默认页显示数量
      pageSize: 20,
      // 选择的页数
      pageCurrent: 1,
      // 存储页面数据
      tableData: [],
      // table左侧选择框选择数组
      multipleSelection: [],
      // 弹窗的显示状态
      dialogVisible: false,
      // 是否在操作列上方显示搜索
      showSearch: true,
      // 搜索的内容
      search: '',
      // 弹窗内容数据设置
      form: {},
      formState: false,
      // 树形控件角色数据设置
      roleOptions: [],
      roleName: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      queryParams: {
        userName: undefined
      }
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView,
      fixedHeader: state => state.settings.fixedHeader
    })
  },
  watch: {
    roleName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.init()
  },
  methods: {
    // 初始化函数
    init() {
      this.loading = true
      getAllRole().then(resp => {
        this.roleOptions = resp.obj
      })
      getAllUser(this.pageSize, this.pageCurrent).then(resp => {
        this.total = resp.obj.total
        this.tableData = resp.obj.list
        this.loading = false
      })
    },
    // 左侧选择框
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    // 删除行
    deleteRow(index, rows) {
      this.deleteConfirm(index, rows)
    },
    // 查看信息
    lookUp(index, rows) {
      this.form = rows[index]
      this.dialogVisible = true
    },
    // 修改信息
    update(index, rows) {
      this.form = rows[index]
      this.formState = true
      this.dialogVisible = true
    },
    // 弹窗表单关闭回调函数
    formClose() {
      this.formState = false
      this.dialogVisible = false
    },
    //  更新二次确认弹窗
    updateConfirm() {
      this.$confirm('确定要更新用户数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateUser(this.form).then(rsp => {
          if (rsp.result) {
            this.$message({
              type: 'success',
              message: '更新成功'
            })
          } else {
            this.$notify({
              title: '操作失败',
              message: '更新用户数据失败，请联系管理员',
              type: 'warning'
            })
          }
          this.dialogVisible = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    //  删除二次确认弹窗
    deleteConfirm(index, rows) {
      this.$confirm('确定要删除此用户账号吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(rows[index].userId).then(rsp => {
          if (rsp.result) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.formState = false
            this.dialogVisible = false
            rows.splice(index, 1)
          } else {
            this.$notify({
              title: '操作失败',
              message: '删除账号失败，请联系管理员',
              type: 'warning'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    // 改变分页数量
    handleSizeChange(val) {
      this.loading = true
      this.pageCurrent = 1
      getAllUser(val, 1).then(resp => {
        this.total = resp.obj.total
        this.tableData = resp.obj.list
        this.loading = false
      })
    },
    // 换页
    handleCurrentChange(val) {
      this.loading = true
      getAllUser(this.pageSize, val).then(resp => {
        this.total = resp.obj.total
        this.tableData = resp.obj.list
        this.loading = false
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.id === 0) {
        return
      }
      console.log('刷新使用', data.id)
    },
    // 增加用户
    handleAdd() {

    },
    // 更新用户信息
    handleUpdate() {

    },
    // 删除用户信息
    handleDelete() {

    },
    // 搜索按钮操作
    handleQuery() {

    },
    // 重置按钮操作
    resetQuery() {
      this.queryParams.userName = ''
    },
    // 用户状态修改
    handleStatusChange(row) {
      this.userStateConfirm(row.userState, row)
    },
    // 弹窗用户账号状态
    handleUserState(index) {
      this.userStateConfirm(index)
    },
    // 账号状态弹窗
    userStateConfirm(index, row) {
      this.$confirm('确定要修改用户状态吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row !== undefined) {
          updateUser(row).then(rsp => {
            if (rsp.result) {
              this.$message({
                type: 'success',
                message: '更新成功'
              })
            } else {
              this.$message({
                type: 'warning',
                message: '更新失败，请联系管理员'
              })
            }
          })
        } else {
          updateUser(this.form).then(rsp => {
            if (rsp.result) {
              this.$message({
                type: 'success',
                message: '更新成功'
              })
            } else {
              this.$message({
                type: 'warning',
                message: '更新失败，请联系管理员'
              })
            }
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
        this.form.userState = index === 0 ? 1 : 0
      })
    }
  }
}
</script>

<style>
 .content {
   margin: 20px;
 }
 .header {
   margin-top: 54px;
 }
</style>
